from django.contrib import admin
from .models import SatelliteSchedule


@admin.register(SatelliteSchedule)
class SatelliteScheduleAdmin(admin.ModelAdmin):
    """
    卫星排程管理界面
    """
    list_display = [
        'satellite', 
        'get_project_name', 
        'get_group_name', 
        'get_task_count', 
        'get_total_duration', 
        'created_at', 
        'updated_at'
    ]
    list_filter = [
        'satellite__group__project', 
        'satellite__group', 
        'created_at', 
        'updated_at'
    ]
    search_fields = [
        'satellite__name', 
        'satellite__group__name', 
        'satellite__group__project__name'
    ]
    readonly_fields = ['created_at', 'updated_at']
    
    def get_project_name(self, obj):
        """获取项目名称"""
        return obj.satellite.group.project.name
    get_project_name.short_description = '所属项目'
    
    def get_group_name(self, obj):
        """获取组名称"""
        return obj.satellite.group.name
    get_group_name.short_description = '所属组'
    
    def get_task_count(self, obj):
        """获取任务块数量"""
        return obj.get_task_count()
    get_task_count.short_description = '任务块数量'
    
    def get_total_duration(self, obj):
        """获取总持续时间"""
        duration = obj.get_total_duration()
        return f'{duration}天' if duration > 0 else '0天'
    get_total_duration.short_description = '总持续时间'
    
    fieldsets = (
        ('基本信息', {
            'fields': ('satellite',)
        }),
        ('排程信息', {
            'fields': ('schedule_info',),
            'description': '存储任务块的详细信息，JSON格式，包括：任务名称、持续时间、需要设备总体、设备容量、每日设备配置、开始时间和结束时间等'
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def get_queryset(self, request):
        """优化查询性能"""
        return super().get_queryset(request).select_related(
            'satellite__group__project'
        )
